package com.mimose.component.redisson.lock.util;

import com.mimose.component.redisson.lock.api.DistributedLocker;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Lock;

/**
 * @Description redisson锁工具类
 * @Author ccy
 * @Date 2019/12/25
 */
public class LockUtil {
    private static DistributedLocker lock;

    public static void setLocker(DistributedLocker locker) {
        LockUtil.lock = locker;
    }

    /**
     * 加锁
     * @param lockKey
     * @return
     */
    public static Lock lock(String lockKey) {
        return lock.lock(lockKey);
    }

    /**
     * 释放锁
     * @param lockKey
     */
    public static void unlock(String lockKey) {
        lock.unlock(lockKey);
    }

    /**
     * 释放锁
     * @param lock
     */
    public static void unlock(Lock lock) {
        LockUtil.lock.unlock(lock);
    }

    /**
     * 带超时的锁
     * @param lockKey
     * @param timeout 超时时间   单位：秒
     */
    public static Lock lock(String lockKey, int timeout) {
        return lock.lock(lockKey, timeout);
    }

    /**
     * 带超时的锁
     * @param lockKey
     * @param unit 时间单位
     * @param timeout 超时时间
     */
    public static Lock lock(String lockKey, TimeUnit unit ,int timeout) {
        return lock.lock(lockKey, unit, timeout);
    }

    /**
     * 尝试获取锁
     * @param lockKey
     * @param waitTime 最多等待时间
     * @param leaseTime 上锁后自动释放锁时间
     * @return
     */
    public static boolean tryLock(String lockKey, int waitTime, int leaseTime) {
        return lock.tryLock(lockKey, TimeUnit.SECONDS, waitTime, leaseTime);
    }

    /**
     * 尝试获取锁
     * @param lockKey
     * @param unit 时间单位
     * @param waitTime 最多等待时间
     * @param leaseTime 上锁后自动释放锁时间
     * @return
     */
    public static boolean tryLock(String lockKey, TimeUnit unit, int waitTime, int leaseTime) {
        return lock.tryLock(lockKey, unit, waitTime, leaseTime);
    }
}
